package service

import (
	"errors"
	"github.com/spf13/cobra"
	"path"
	"strings"
)

type Handler struct {
	cmd     *cobra.Command
	args    []string
	options *Options
}

func NewHandler(cmd *cobra.Command, args []string) *Handler {
	handler := &Handler{
		cmd:  cmd,
		args: args,
	}
	return handler
}

func (h *Handler) Exec() error {
	for _, serviceArg := range h.args {
		if path.IsAbs(serviceArg) {
			return errors.New("需要相对路径作为服务将安装在GOPATH中，请勿输入以‘/’开头的项目路径")
		}
		serviceSlice := strings.Split(serviceArg, "/")
		serviceName := serviceSlice[len(serviceSlice)-1]
		if len(serviceName) == 0 {
			return errors.New("服务名称格式错误")
		}
		// 构建对象
		builder := NewBuilder(NewOptions(serviceName, serviceArg))
		// 构建
		_ = builder.build()
	}
	return nil

}
